let dbConfig = require('../utils/dbConfig')
let fs=require('fs')
const jwToken = require('jsonwebtoken')
const secretKey = 'lambyt2021'

//评论加一
let CommentNumPlus=async(momentID)=>{
  let sql='update moment set collected=collected+1 where momentID=?'
  let sqlArr=[momentID]
  const res=await dbConfig.SySqlConnect(sql,sqlArr)
  if(res.affectedRows===1){
    return true
  }else{
    return false
  }
}
// 获取校友圈信息
getCarousel=(req,res)=>{
  let sql='select * from carousel'
  let sqlArr=[]
  var callBack = (err, data) => {
    if (err) {
      console.log("连接出错了")
    } else {
      res.send({
        'code': 200,
        'data': data,
        'msg': "获取轮播图成功"
      })
    }
  }
  dbConfig.sqlConnect(sql, sqlArr, callBack)
}
getHot=(req,res)=>{
  let sql='select * from moment order by liked desc limit 5'
  let sqlArr=[]
  let callBack = (err, data) => {
    if (err) {
      console.log(err)
    } else {
      res.send({
        'code': 200,
        'data': data,
        'msg': "获取数据成功"
      })
    }
  }
  dbConfig.sqlConnect(sql, sqlArr, callBack)
}
getMomentAll = (req, res) => {
  const token = (req.headers.authorization || '').slice(7)
  try {
    const decoded = jwToken.verify(token, secretKey);
    console.log(decoded)
  } catch (error) {
    res.send({
      'code': 401,
      'tip': '请登录',
      'msg': 'token错误，请重新登录'
    })
  }
  let type = req.query.type
  if (type == 0) {
    var sql = "select * from moment order by time desc"
    var sqlArr = []
  } else {
    var sql = "select * from moment where type=? order by time desc"
    var sqlArr = [type]
  }
  var callBack = (err, data) => {
    if (err) {
      console.log("连接出错了")
    } else {
      res.send({
        'code': 200,
        'data': data,
        'msg': "获取数据成功"
      })
    }
  }
  dbConfig.sqlConnect(sql, sqlArr, callBack)
}
getSearch=(req,res)=>{
  let {value}=req.query
  let sql=`select * from moment where content like '%${value}%'`
  let sqlArr=[]
  let callBack=(err, data) => {
    if (err) {
      console.log(err)
    } else {
      res.send({
        'code': 200,
        'data': data
      })
    }
  }
  dbConfig.sqlConnect(sql, sqlArr, callBack)
}
getMomentByID = (req, res) => {
  let { momentID } = req.query
  let sql = 'select * from moment where momentID in (?)'
  let sqlArr = [momentID]
  let callBack = (err, data) => {
    if (err) {
      console.log(err)
    } else {
      res.send({
        'code': 200,
        'data': data,
        'msg': "获取数据成功"
      })
    }
  }
  dbConfig.sqlConnect(sql, sqlArr, callBack)
}
getMomentsLike = (req, res) => {
  let userID = req.query.userID
  let sql = 'select * from moment,user_like where moment.momentID=user_like.momentID and user_like.userID=? order by user_like.time desc'
  let sqlArr = [userID]
  let callBack = (err, data) => {
    if (err) {
      console.log(err)
    } else {
      res.send({
        'code': 200,
        'data': data,
        'msg': "获取数据成功"
      })
    }
  }
  dbConfig.sqlConnect(sql, sqlArr, callBack)
}
getMomentsReleased = (req, res) => {
  let userID = req.query.userID
  let sql = 'select * from moment where userID=? order by time desc'
  let sqlArr = [userID]
  let callBack = (err, data) => {
    if (err) {
      console.log(err)
    } else {
      res.send({
        'code': 200,
        'data': data,
        'msg': "获取数据成功"
      })
    }
  }
  dbConfig.sqlConnect(sql, sqlArr, callBack)
}
getMyGoodsOrder=(req,res)=>{
  let { userID } = req.query
  let sql='select * from user_order where sellerID=? order by create_time desc'
  let sqlArr=[userID]
  let callBack = (err, data) => {
    if (err) {
      console.log(err)
    } else {
      res.send({
        'code': 200,
        'data': data,
        'msg': "获取数据成功"
      })
    }
  }
  dbConfig.sqlConnect(sql, sqlArr, callBack)
}
deleteMoment = async (req, res) => {
  let momentID = req.query.momentID
  let sql = 'delete from moment where momentID=?'
  let sqlvice = 'delete from moment_comment where momentID=?'
  let sqlArr = [momentID]
  let result = await dbConfig.SySqlConnect(sql, sqlArr)
  let resultvice = await dbConfig.SySqlConnect(sqlvice, sqlArr)
  console.log(resultvice.affectedRows)
  if (result.affectedRows == 1 && resultvice.affectedRows >= 0) {
    res.send({
      'code': 200,
      'tip': '删除成功'
    })
  } else {
    res.send({
      'code': 400,
      'tip': '删除失败'
    })
  }
}
handleLike = async (req, res) => {
  let { operation, userID, momentID } = req.body
  if (operation === 'add') {
    var sql1 = "update moment set liked = liked+1 where momentID=?"
    var sql2 = "insert into user_like(userID,momentID,time) values(?,?,?)"
    var sqlArr2 = [userID, momentID, (new Date()).valueOf()]
  } else {
    var sql1 = "update moment set liked = liked-1 where momentID=?"
    var sql2 = "delete from user_like where userID=? and momentID=?"
    var sqlArr2 = [userID, momentID]
  }
  var sqlArr1 = [momentID]
  let result = await dbConfig.SySqlConnect(sql1, sqlArr1)
  var result2 = await dbConfig.SySqlConnect(sql2, sqlArr2)
  if (result.affectedRows == 1 && result2.affectedRows == 1) {
    res.send({
      'code': 200,
      'tip': "感谢你的喜欢"
    })
  } else {
    res.send({
      'code': 400,
      'tip': "喜欢失败"
    })
  }
}
getComments = (req, res) => {
  let { momentID } = req.query
  let sql = 'select * from moment_comment where momentID=?'
  let sqlArr = [momentID]
  let callBack = (err, data) => {
    if (err) {
      console.log("连接出错了")
    } else {
      res.send({
        'code': 200,
        'data': data,
        'msg': "获取评论成功"
      })
    }
  }
  dbConfig.sqlConnect(sql, sqlArr, callBack)
}
saveComment = async (req, res) => {
  let { momentID, userID, comment } = req.body
  let info = await getNickname(userID)
  let nickname = info[0].nickname
  let sql = 'insert into moment_comment(momentID,reply_userID,reply_nickname,comment) values(?,?,?,?)'
  let sqlArr = [momentID, userID, nickname, comment]
  let result = await dbConfig.SySqlConnect(sql, sqlArr)
  let Plus=await CommentNumPlus(momentID)
  if (result.affectedRows === 1&&Plus) {
    res.send({
      'code': 200,
      'msg': '回复成功'
    })
  } else {
    res.send({
      'code': 400,
      'msg': '回复失败'
    })
  }
}
addToCart = async (req, res) => {
  let { momentID, userID, type } = req.body
  let sql = (type === 'add') ? 'insert into user_cart(userID, momentID,time) values(?,?,?)' : 'delete from user_cart where userID=? and momentID=?'
  let sqlArr = [parseInt(userID), parseInt(momentID),(new Date()).valueOf()]
  let result = await dbConfig.SySqlConnect(sql, sqlArr)
  if (result.affectedRows&&result.affectedRows === 1) {
    res.send({
      'code': 200,
      'msg': '添加成功'
    })
  } else {
    res.send({
      'code': 400,
      'msg': '添加失败'
    })
  }
}
getMomentType = (req, res) => {
  let sql = "select * from moment_type"
  let sqlArr = []
  let callBack = (err, data) => {
    if (err) {
      console.log("连接出错了")
    } else {
      res.send({
        'code': 200,
        'data': data,
        'msg': "获取校友圈分类成功"
      })
    }
  }
  dbConfig.sqlConnect(sql, sqlArr, callBack)
}
saveMoment = async (req, res) => {
  let { userID, type, content, price } = req.body
  if(price==='') price=null
  let files = req.files
	console.log(files)
  let fileList=''
  for(let i in files){
    let file = files[i];
    fs.renameSync('./public/uploads/' + file.filename, './public/uploads/' + file.originalname)
    fileList=fileList+`http://localhost:3000/uploads/${file.originalname};`
  }
  let info = await getNickname(userID)
  let { avator, nickname, Class } = info[0]
  let sql = 'insert into moment(type,userID,nickname,avator,Class,content,fileList,time,price) values(?,?,?,?,?,?,?,?,?)'
  let sqlArr = [type, userID, nickname, avator, Class, content, fileList, (new Date()).valueOf(),price]
  let result = await dbConfig.SySqlConnect(sql, sqlArr)
  if (result.affectedRows === 1) {
    res.send({
      'code': 200,
      'msg': "发布成功"
    })
  } else {
    res.send({
      'code': 400,
      'msg': "发布失败"
    })
  }
}
saveFriend = async (req, res) => {
  let { friendID, userID } = req.body
  let sql = 'insert into user_care(userID,careID,time) values(?,?,?)'
  let sqlArr = [userID, friendID, (new Date()).valueOf()]
  let result = await dbConfig.SySqlConnect(sql, sqlArr)
  if (result.affectedRows === 1) {
    res.send({
      'code': 200,
      'tip': '添加成功'
    })
  } else {
    res.send({
      'code': 400,
      'tip': '添加失败'
    })
  }
}
upload = (req, res) => {
  if (req.file.length === 0) {
		res.render("error", { message: "上传文件不能为空" })
		return
	} else {
		let file = req.file
		console.log(file)
		fs.renameSync('./public/uploads/' + file.filename, './public/uploads/' + file.originalname)
    res.send({
      'code':200
    })

		
	}

}
let getNickname = (userID) => {
  let sql = 'select nickname,avator,Class from user where userID=?'
  let sqlArr = [userID]
  return dbConfig.SySqlConnect(sql, sqlArr)
}


module.exports = {
  getCarousel,
  getHot,
  getMomentAll,
  getSearch,
  getMomentByID,
  getMomentsLike,
  getMomentsReleased,
  deleteMoment,
  getMyGoodsOrder,
  handleLike,
  saveComment,
  getComments,
  addToCart,
  getMomentType,
  saveMoment,
  saveFriend,
  upload
}